import { EntityManager, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import {
  InternalServerErrorException,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { Theme } from './entities/theme.entity';
import { CreateThemeDto } from './dto/create-theme.dto';
import { Background } from './entities/theme-back.entity';
import { Bar } from './entities/theme-bar.entity';
import { Custom } from './entities/theme-custom.entity';
import { Button } from './entities/theme-butt.entity';
import { User } from '../user/entities/user.entity';
import { ThemeFilterDto } from './dto/themeFilterDto';
import { UpdateThemeDto } from './dto/update-theme.dto';
import { Config } from './entities/theme-config.entity';
import { IPaginationOptions, paginate, Pagination } from '../utils/paginate';
import { ThemeBindUserDto } from './dto/bind-user.dto';
export class ThemeRepository {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  private logger = new Logger('TasksRepository', true);
  // private background = BackgroundRepository;
  constructor(
    @InjectRepository(Theme)
    private repository: Repository<Theme>,
    private entityManage: EntityManager,
  ) {}
  async getThemeList(
    themeFilterDto: ThemeFilterDto,
    user: User,
    options: IPaginationOptions,
  ): Promise<Pagination<Theme>> {
    const { search } = themeFilterDto;
    const query = this.repository
      .createQueryBuilder('theme')
      .leftJoinAndSelect('theme.background', 'background')
      .leftJoinAndSelect('theme.custom', 'custom')
      .leftJoinAndSelect('theme.bar', 'bar')
      .leftJoinAndSelect('theme.button', 'button')
      .leftJoinAndSelect('theme.config', 'config');
    // if (user.username !== 'admin') {
    //   query.where({ user });
    // }
    // if (status) {
    //   query.andWhere('task.status = :status', { status });
    // }
    if (search) {
      query.where(
        // OR LOWER(task.description) LIKE LOWER(:search)
        '(LOWER(theme.name) LIKE LOWER(:search))',
        { search: `%${search}%` },
      );
    }
    query.andWhere('theme.isDelete = 0');
    try {
      // const themes = await query.getMany();
      // const themes = await paginate<Theme>(query, options);
      return await paginate<Theme>(query, options);
    } catch (error) {
      this.logger.error(
        `Faild to get task for user "${
          user.username
        }". Filter: ${JSON.stringify(themeFilterDto)}`,
        error.stack,
      );
      throw new InternalServerErrorException('服务器内部错误!');
    }
  }
  async getThemeById(id: string): Promise<Theme> {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    // 添加user后将获取当前用户的数据，使用其它用户的任务id将返回404
    const found = await this.repository
      .createQueryBuilder('theme')
      .leftJoinAndSelect('theme.background', 'background')
      .leftJoinAndSelect('theme.custom', 'custom')
      .leftJoinAndSelect('theme.bar', 'bar')
      .leftJoinAndSelect('theme.button', 'button')
      .leftJoinAndSelect('theme.config', 'config')
      .where('theme.id = :id and theme.isDelete = 0', { id: id })
      .getOne();
    if (!found) {
      throw new NotFoundException(`参数${id}没有找到！`);
    }
    return found;
  }
  async createTheme(
    createThemeDto: CreateThemeDto,
    user: User,
  ): Promise<string> {
    const {
      // eslint-disable-next-line prefer-const
      name,
      status,
      background: background1,
      custom: custom1,
      bar: bar1,
      button: button1,
      config: config1,
    } = createThemeDto;
    let db = await this.entityManage
      .getRepository(Background)
      .create(background1);
    const background = await this.entityManage
      .getRepository(Background)
      .save(db);
    db = await this.entityManage.getRepository(Custom).create(custom1);
    const custom = await this.entityManage.getRepository(Custom).save(db);
    db = await this.entityManage.getRepository(Bar).create(bar1);
    const bar = await this.entityManage.getRepository(Bar).save(db);
    db = await this.entityManage.getRepository(Button).create(button1);
    const button = await this.entityManage.getRepository(Button).save(db);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    db = await this.entityManage.getRepository(Config).create(config1);
    const config = await this.entityManage.getRepository(Config).save(db);
    const theme = this.repository.create({
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      name,
      status,
      background,
      custom,
      bar,
      button,
      config,
      user,
    });
    await this.repository.save(theme);
    return '创建成功！';
  }
  async deleteTheme(id: string): Promise<void> {
    const theme = await this.getThemeById(id);
    const result = await this.repository.delete({ id });
    await this.entityManage
      .getRepository(Background)
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      .delete(theme.background.id);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    await this.entityManage.getRepository(Custom).delete(theme.custom.id);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    await this.entityManage.getRepository(Bar).delete(theme.bar.id);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    await this.entityManage.getRepository(Button).delete(theme.button.id);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    await this.entityManage.getRepository(Config).delete(theme.config.id);
    if (result.affected === 0) {
      throw new NotFoundException(`参数 ${id} 没有找到！`);
    }
  }
  async updateTheme(updateThemeDto: UpdateThemeDto): Promise<Theme> {
    const { id, background, custom, bar, button, name, status, config } =
      updateThemeDto;
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (background.id) {
        await this.entityManage
          .getRepository(Background)
          .createQueryBuilder('background')
          .update(Background)
          .set(background)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          .where('id = :id ', { id: background.id })
          .execute();
      }
    } catch (e) {}
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (custom.id) {
        await this.entityManage
          .getRepository(Custom)
          .createQueryBuilder('custom')
          .update(Custom)
          .set(custom)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          .where('id = :id ', { id: custom.id })
          .execute();
      }
    } catch (e) {}
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (bar.id) {
        await this.entityManage
          .getRepository(Bar)
          .createQueryBuilder('bar')
          .update(Bar)
          .set(bar)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          .where('id = :id ', { id: bar.id })
          .execute();
      }
    } catch (e) {}
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (button.id) {
        await this.entityManage
          .getRepository(Button)
          .createQueryBuilder('background')
          .update(Button)
          .set(button)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          .where('id = :id ', { id: button.id })
          .execute();
      }
    } catch (e) {}
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (config.id) {
        await this.entityManage
          .getRepository(Config)
          .createQueryBuilder('config')
          .update(Button)
          .set(config)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          .where('id = :id ', { id: config.id })
          .execute();
      }
    } catch (e) {}

    await this.repository
      .createQueryBuilder('theme')
      .update(Theme)
      .set({ id, status, name })
      .where('id = :id', { id: id })
      .execute();
    return this.getThemeById(id);
  }

  async bindUsers(data: ThemeBindUserDto): Promise<string> {
    const { userId, themeId } = data;
    const theme = await this.repository.findOneBy({ id: themeId });
    const user = await this.entityManage
      .getRepository(User)
      .findOneBy({ id: userId });
    user.theme = theme;
    await this.entityManage.getRepository(User).save(user);
    return '绑定成功！';
  }
}
